/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ControllerAjax;

import Main.StaticParams;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.Collection;
import java.util.GregorianCalendar;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 *
 * @author Sik
 */
@WebServlet(name = "ControllerFile", urlPatterns =
{
    "/File/*"
})
@MultipartConfig(location = StaticParams.TEMP_FILE_PATH, fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class ControllerFile extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String pathInfo = request.getPathInfo();

        if (pathInfo.equals("/upload"))
        {
            File f = new File(StaticParams.TEMP_FILE_PATH);
            if (!f.isDirectory())
            {
                f.mkdir();
            }
            
            String filename = "";
            String username = request.getUserPrincipal().getName();
            Collection<Part> parts = request.getParts();
            GregorianCalendar gc = new GregorianCalendar();
            
            String dirPath = StaticParams.DESTINATION_FILE_PATH + "/" + username  + gc.getTimeInMillis();
            for(Part part : parts)
            {
                try
                {
                    
                    filename = extractFileNameFromHeader(part);
                    part.write(filename);
                    File sourcePath = new File(StaticParams.TEMP_FILE_PATH + "/" + filename);
                    System.out.println("src : " + sourcePath);
                    
                    File destPath = new File(getServletContext().getRealPath("/") + dirPath);
                    destPath.mkdirs();
                    destPath = new File(getServletContext().getRealPath("/") + dirPath + "/"+ filename);
                    
                    moveFile(sourcePath, destPath);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                break;
            }
            
            System.out.println(request.getContextPath());
            RequestDispatcher rd = getServletContext().getContext(request.getContextPath()).getRequestDispatcher("/Map/add");
            request.setAttribute("designation", "Nouvelle Carte");
            request.setAttribute("filename", filename);
            request.setAttribute("path", dirPath + "/" + filename);
            rd.forward(request, response);
        }
    }

    private boolean copyFile(String sourceFileName, String destinationFileName)
    {
        FileChannel in = null; 
        FileChannel out = null; 

        try
        {
            in = new FileInputStream(sourceFileName).getChannel();
            out = new FileOutputStream(destinationFileName).getChannel();
            in.transferTo(0, in.size(), out);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        { 
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                    return true;
                }
                catch (IOException e)
                {
                }
            }
            return false;
        }
    }

    private boolean moveFile(File source, File destination)
    {
        if (!destination.exists())
        {
            boolean result = source.renameTo(destination);
            if (!result)
            {
                result = true;
                result &= copyFile(source.getAbsolutePath(), destination.getAbsolutePath());
                if (result)
                {
                    result &= source.delete();
                }

            }
            return (result);
        }
        else
        {
            return (false);
        }
    }
    
    private String extractFileNameFromHeader(Part part)
    {
        String filename = null;
        String header = part.getHeader("content-disposition");
        String[] attributes = header.split(";");
        for(String s : attributes)
        {
            if(s.contains("filename"))
            {
                filename = s.substring(s.indexOf('"')+1, s.lastIndexOf('"'));
            }
        }
        return filename;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
